﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SHelper
{
    class SqlHelper
    {
        //从config配置文件中获得连接字符串connstr
        private static string connstr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        
        /// <summary>
        /// 非查询操作
        /// </summary>
        public static int ExecuteNonQuery(string sql, string ConnectionString, params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    //cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteNonQuery();
                }
            }
        }
        /// <summary>
        /// 单值查询操作
        /// </summary>
        public static object ExecuteScalar(string sql, string ConnectionString, params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    //cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteScalar();
                }
            }
        }
        /// <summary>
        /// 多行查询操作
        /// </summary>
        public static System.Data.DataTable ExecuteDataTable(string sql, string ConnectionString, params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    //cmd.Parameters.AddRange(parameters);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataSet dataset = new DataSet();
                    adapter.SelectCommand.CommandTimeout = 300;
                    adapter.Fill(dataset);
                    return dataset.Tables[0];
                }
            }
        }
    }
}
